qui(
    function (require, exports, module) {
        Broadcast.Edit = function (options) {
            this.dao = Broadcast.Dao;
            this.task = Broadcast.Task;
            this.config = Broadcast.Config;
            this.options = options || {};
        };
        Com.inherits(Broadcast.Edit, Ancestor.Grid).extend({
            channelRun: function () {
                $("#buttonDiv").hide();
                $("#hintPart").hide();
                var channelId = Com.url.getParameter("id");
                if (channelId == null || isNaN(channelId)) {
                    EpgWeb.Plugin.showTips({content: "need channelId", type: "error"})
                    return;
                }
                var self = this;
                self.initDialog();
                Broadcast.Config.Mode = self.options.model;
                self.dao.channelId = parseInt(channelId);
                var taskArr = [];
                taskArr.push(self.task.getPlayPlatform(self.dao.cfgName.PlayPlatform, function (data) {
                    self.fillNavBar(data);
                }));
                taskArr.push(self.task.getChannel(self.dao.cfgName.getChannel, self.dao.channelId));
                taskArr.push(self.task.getBroadcastTask(self.dao.cfgName.broadcastControl, self.dao.channelId));
                $.each(taskArr, function (index, element) {
                    EpgWeb.ajaxQueue.push(element.regName, element.options);
                })

                EpgWeb.ajaxQueue.afterLoadComplete(function () {
                    self.initTypeChannel();
                });
                EpgWeb.ajaxQueue.startLoad();
            },

            initTypeChannel: function () {
                console.log("init end");
                var self = this;
                self.initPanelContainer();
                self.bindClickHandler();
                self.fillInitTabPanelDefault();
                self.fillInitTabPanel();
                self.initBlacklistDefault();
                self.initSuggestChannel();

                //self.initLocationAreaMask();

            },
            fillNavBar: function (data) {
                if (data != null) {
                    console.log(data.code);
                }
                if (data != null && data.code == "A00000") {
                    var navDiv = $("#navDiv");
                    var ulPart = $("<ul></ul>");
                    var createDate = data.data;
                    $("<li hidden><a href='#tabPanel_0'>0</a></li>").appendTo(ulPart);
                    $.each(createDate, function (index, obj) {
                        $("<li><a href='#tabPanel_" + obj.key + "'>" + obj.descr + "</a></li>").appendTo(ulPart);
                    })
                    ulPart.prependTo(navDiv);
                    navDiv.find("ul").hide();
                }
            },
            bindClickHandler: function () {
                var self = this;
                $("input[name=clientSetting]").click(function (event) {
                    if (event.currentTarget.value == 0) {
                        $("#navDiv").tabs({active: 0});
                        $("#navDiv").find("ul").hide();
                    } else {
                        $("#navDiv").tabs({active: 1});
                        $("#navDiv").find("ul").show();
                    }
                })
                $("input[name=submitBtn]").click(function (event) {
                    if(self.submitFun()){
                        $("input[name=submitBtn]").attr("disabled", "disabled")
                    }
                    // Broadcast.Dao.submitFun(false)
                });
                $("input[name=area_select]").click(function (event) {
                    var jObj = $(event.currentTarget.parentNode.parentNode);
                    var child = $(event.currentTarget);
                    var selectArr = Broadcast.Util.formatToLocationItem(child.val());
                    var suggestInput = jObj.parent().find("input[name=localSuggest]");
                    if (child.prop("checked") == true) {
                        for (var i = 0; i < selectArr.length; i++) {
                            suggestInput.suggest("addValue", selectArr[i]);
                        }
                    } else {
                        for (var i = 0; i < selectArr.length; i++) {
                            var el = suggestInput.parent().find("span[data-tag-id=" + selectArr[i].id + "]").find("a");
                            if (el.length > 0) {
                                suggestInput.suggest("removeValue", el);
                            }
                        }
                    }
                })
            },
            submitFun: function () {
                var self = this;
                var copyToAll = $("input[name=clientSetting]:checked").val() == 0
                if (self.options.model == "channel") {
                    var $showTabPanel = $("div[aria-hidden=false]");
                    var assignToPrograms = $showTabPanel.find("input[name=app_on_episode]:checked").val();
                    if (null == assignToPrograms) {
                        EpgWeb.Plugin.showTips({content: "频道播控是否立即对节目生效 必填", type: "error"})
                        return false;
                    }
                    self.doSaveData(copyToAll);
                } else if (self.options.model == "episode") {
                    self.doSaveEpisodeData(copyToAll);
                }
                return true;
            },
            doSaveData: function (copyToAll) {
                var self = this;
                var $showTabPanel = $("div[aria-hidden=false]")
                var locationControl = $showTabPanel.find("div[name=locationControl]");
                var onlineValue = locationControl.find("input[type=radio]:checked").val();
                var rejectSearchValue = locationControl.find("input[name=rejectSearch]").prop("checked") == true;
                var regionRejectSearchValue = locationControl.find("input[name=regionRejectSearch]").prop("checked") == true;
                var delayValue = locationControl.find("input[name$=delay]").val()
                var locationResult = locationControl.find(".tagmanagerTag")
                var saveBlackList = [];
                $.each(locationResult, function (index, obj) {
                    saveBlackList.push(obj.getAttribute("data-tag-id") + "_" + obj.getAttribute("data-tag-label"))
                })

                var sendData = {channelId: self.dao.channelId, params: null, assignToPrograms: "" };
                var assignToPrograms = $("input[name=app_on_episode]:checked").val();
                sendData.assignToPrograms = assignToPrograms || "";

                var platformKey = parseInt($showTabPanel.attr("id").split("_")[1]);
                var entityData = self.dao.createControlData();
                entityData.platform = platformKey;
                entityData.blacklist = saveBlackList.join(",");
                entityData.rejectSearch = rejectSearchValue;
                if ($.trim(delayValue).length == 0 || isNaN(delayValue)) {
                    entityData.liveDelayTime = 0;
                } else {
                    entityData.liveDelayTime = parseInt($.trim(delayValue));
                }
                entityData.availableStatus = parseInt(onlineValue) == 1 ? true : false;
                entityData.regionRejectSearch = regionRejectSearchValue
                var dataArr = [];
                if (copyToAll) {
                    var responseData = self.dao.getPlatforms();
                    var createDate = responseData.data;
                    var platformArr = [];
                    $.each(createDate, function (index, obj) {
                        platformArr.push(obj.key)
                    })
                    sendData.platforms = JSON.stringify(platformArr);
                    sendData.params = JSON.stringify(entityData);
                } else {
                    dataArr.push(entityData);
                    sendData.params = JSON.stringify(dataArr);
                }
                console.log("sendData:" + JSON.stringify(sendData));
                self.dao.saveData(copyToAll, sendData, function (data) {
                    self.submitCallHandler(data,copyToAll);
                })
            },

            doSaveEpisodeData: function (copyToAll) {
                var self = this;
                var $showTabPanel = $("div[aria-hidden=false]")
                var locationControl = $showTabPanel.find("div[name=locationControl]");
                var onlineValue = locationControl.find("input[type=radio]:checked").val();
                var rejectSearchValue = locationControl.find("input[name=rejectSearch]").prop("checked") == true;
                var regionRejectSearchValue = locationControl.find("input[name=regionRejectSearch]").prop("checked") == true;
                var delayValue = locationControl.find("input[name$=delay]").val()
                var locationResult = locationControl.find(".tagmanagerTag")
                var saveBlackList = [];
                $.each(locationResult, function (index, obj) {
                    saveBlackList.push(obj.getAttribute("data-tag-id") + "_" + obj.getAttribute("data-tag-label"))
                })
                var sendData = {programId: self.dao.programId, params: null, channelId: self.dao.channelId }
                var platformKey = parseInt($showTabPanel.attr("id").split("_")[1]);
                var entityData = self.dao.createControlData();
                entityData.platform = platformKey;
                entityData.blacklist = saveBlackList.join(",");
                entityData.rejectSearch = rejectSearchValue;
                entityData.liveDelayTime = 0;
                entityData.availableStatus = parseInt(onlineValue) == 1 ? true : false;
                entityData.regionRejectSearch = regionRejectSearchValue
                var dataArr = [];
                if (copyToAll) {
                    var responseData = self.dao.getPlatforms();
                    var createDate = responseData.data;
                    var platformArr = [];
                    $.each(createDate, function (index, obj) {
                        platformArr.push(obj.key)
                    })
                    sendData.platforms = JSON.stringify(platformArr);
                    sendData.params = JSON.stringify(entityData);
                } else {
                    dataArr.push(entityData);
                    sendData.params = JSON.stringify(dataArr);
                }

                if (copyToAll) {
                    var responseData = self.dao.getPlatforms();
                    var createDate = responseData.data;
                    var platformArr = [];
                    $.each(createDate, function (index, obj) {
                        platformArr.push(obj.key)
                    })
                    sendData.platforms = JSON.stringify(platformArr);
                    sendData.params = JSON.stringify(entityData);
                } else {
                    sendData.params = JSON.stringify(entityData);
                }
                console.log("sendData:" + JSON.stringify(sendData));
                self.dao.saveEpisodeData(copyToAll, sendData, function (data) {
                    self.submitCallHandler(data,copyToAll);
                })
            },
            submitCallHandler: function (data,copyToAll) {
                if (data != null) {
                    console.log("data" + data.msg);
                    if (data.code == "A00000") {
                        EpgWeb.Plugin.showTips({content: data.msg })
                        if (copyToAll) {
                            $("#refreshMessage").dialog("open")
                            setTimeout(function () {
                                location.reload()
                            }, 1500)
                        }
                    } else {
                        EpgWeb.Plugin.showTips({content: data.msg, type: "error" })
                    }
                } else {
                    EpgWeb.Plugin.showTips({content: "提交数据发生异常", type: "error"})
                }
                $("input[name=submitBtn]").removeAttr("disabled", "disabled")
            },
            fillInitTabPanelDefault: function () {
                var tabPanelArr = $("div[id^=tabPanel_]");
                $.each(tabPanelArr, function (index, obj) {
                    tabPanelArr.find("input[type=radio][value=0]").prop("checked", true);
                    tabPanelArr.find("input[name$=delay]").val(0);
                })
            },
            fillInitTabPanel: function () {
                var self = this;
                var responseData = null;
                if (self.options.model == "channel") {
                    responseData = self.dao.getBroadcastControls();
                    if (responseData.data.length == 0) {
                        return;
                    }
                } else if (self.options.model == "episode") {
                    responseData = self.dao.getProgramBroadcastControls();
                    if (responseData.data.length == 0) {
                        responseData = self.dao.getBroadcastControls();
                        return;
                    }
                }
                responseData.data.sort(function (a, b) {
                    return a.platform > b.platform ? 1 : -1;
                })
                var totalLength =  Broadcast.Dao.getPlatforms().data.length;
                var isSame = responseData.data.length > 1;
                var fetchTarget = null;
                $.each(responseData.data, function (index, obj) {
                    obj.unicodeSign = Broadcast.Util.formatCompareString(obj);
                    if (fetchTarget == null) {
                        fetchTarget = obj;
                    } else if (isSame) {
                        isSame = fetchTarget.unicodeSign == obj.unicodeSign;
                        if (!isSame) {
                            fetchTarget = obj;
                        }
                    }
                    self.fillPanelData(obj)
                });
                isSame = isSame && responseData.data.length == totalLength;
                if (isSame) {
                    self.fillPanelData(fetchTarget, 0)
                } else {
                    $("input[name=clientSetting][value=" + 1 + "]").click();
                    $("#navDiv").tabs({active: fetchTarget.platform});
                }
            },
            fillPanelData: function (obj, index) {
                if (index == null) {
                    index = obj.platform
                }
                var newTarget = $("#tabPanel_" + index);
                var onlineValue = obj.availableStatus ? 1 : 0;
                newTarget.find("input[type=radio][value=" + onlineValue + "]").prop("checked", true);

                if (obj.blacklist.length > 0) {
                    newTarget.find("input[name=localSuggest]").val(obj.blacklist);
                }
                //else{
                //    var channel = Broadcast.Dao.getChannel();
                //    var blacklist = '';
                //    if(channel['type'] == 5) {
                //        blacklist = '3_228_台湾';
                //        newTarget.find("input[name=localSuggest]").val(blacklist);
                //    }else if(channel['type'] == 11) {
                //        blacklist = '3_2_上海,3_1_北京,4_3001_广州,4_3003_深圳,3_4_天津,3_31_西藏,3_30_甘肃,3_26_云南,3_6_山东,3_3_广东,3_22_新疆,3_7_河北,3_10_浙江,3_19_江苏,3_29_青海,3_12_安徽,3_18_贵州,3_16_福建,3_11_湖北,3_28_宁夏,3_15_内蒙古,3_25_海南,3_17_辽宁,3_21_吉林,3_24_黑龙江,3_8_山西,3_13_陕西,3_20_四川,3_5_重庆,3_14_江西,3_27_湖南,6_301_海外,3_148_澳门,3_95_香港';
                //        newTarget.find("input[name=localSuggest]").val(blacklist);
                //    }
                //}
                newTarget.find("input[name$=delay]").val(obj.liveDelayTime);
                if (obj.rejectSearch == true) {
                    newTarget.find("input[name=rejectSearch]").prop("checked", true)
                }
                if (obj.regionRejectSearch == true) {
                    newTarget.find("input[name=regionRejectSearch]").prop("checked", true)
                }
            },
            initSuggestChannel: function () {
                var self = this;
                var options = {
                    source: EpgWeb.urlConfig.redirect,
                    parseValue: function () {
                        var self = this;
                        var val = this.element.val(),
                            ret = [],
                            items = null,
                            itemData = null,
                            options = self.options;

                        if (val) {
                            items = val.split(',');
                            $.each(
                                items, function (i, item) {
                                    item = item.split('_');
                                    itemData = {};
                                    itemData[options.labelKey] = Broadcast.Util.fixLocaltion(item[2]);
                                    itemData[options.valueKey] = item[0] + "_" + item[1];
                                    ret.push(itemData);
                                }
                            );
                        }
                        this._value('');
                        return ret;
                    },
                    process: function (json) {
                        var ret = [],
                            self = this,
                            options = self.options,
                            itemData = null;
                        var data = null;
                        if (json.code === "A00000") {
                            data = $.isArray(json) ? json : json.data;
                        }
                        if (!data) {
                            return [];
                        }
                        $.map(data, function (item) {
                            itemData = {};
                            itemData[options.valueKey] = item["type"] + "_" + item["code"];
                            itemData[options.labelKey] = item["originalName"];
                            ret.push(itemData);
                        });
                        return ret;
                    },
                    method: "post",
                    getParam: function (owner, term) {
                        var requestData = {url: EpgWeb.Constant.third_location_url, type: "get", params: {word: this.element.val()}};
                        return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                    },
                    template: function (item) {
                        return '<div class="contract-item" >' + item.label + '</div>';
                    }
                }
                $("input[name=localSuggest]").suggest(options);

                //self.initBlacklistDefault();
            },

            initBlacklistDefault: function() {
                var channel = Broadcast.Dao.getChannel();
                var controls = $('input[name=localSuggest]');
                var blacklist = '';
                if(channel['type'] == 5) {
                    blacklist = '3_228_台湾';
                } else if(channel['type'] == 11) {
                    blacklist = '3_2_上海,3_1_北京,4_3001_广州,4_3003_深圳,3_4_天津,3_31_西藏,3_30_甘肃,3_26_云南,3_6_山东,3_3_广东,3_22_新疆,3_7_河北,3_10_浙江,3_19_江苏,3_29_青海,3_12_安徽,3_18_贵州,3_16_福建,3_11_湖北,3_28_宁夏,3_15_内蒙古,3_25_海南,3_17_辽宁,3_21_吉林,3_24_黑龙江,3_8_山西,3_13_陕西,3_20_四川,3_5_重庆,3_14_江西,3_27_湖南,6_301_海外,3_148_澳门,3_95_香港';
                }
                if(blacklist != '') {
                    $.each(controls, function(index, e) {
                        $(e).val(blacklist);
                    })
                }
            },
            initDialog: function () {
                var self = this;
                $("#refreshMessage").dialog({
                    title: "等待页面刷新",
                    autoOpen: false,
                    width: 300,
                    modal: true,
                    dialogClass: 'alert',
                    resizable: false
                });
                $("#saveMessage").dialog({
                    title: "同步数据保存",
                    resizable: false,
                    dialogClass: 'alert',
                    autoOpen: false,
                    width: 300,
                    modal: true,
                    buttons: {
                        "确定": function () {
                            self.submitFun();
                            $(this).dialog("close");
                        },
                        "取消": function () {
                            $(this).dialog("close");
                        }
                    }
                });
            },

//==================initTypeChannel end=============//

//==================com method end=============//
            initPanelContainer: function () {
                var self = this;
                var channelEntity = self.dao.getChannel();
                if (channelEntity.liveType == 2) {
                    $("#hintPart").show();
                }
                var htmlArr = [];
                var responseData = self.dao.getPlatforms();
                var createDate = responseData.data;
                htmlArr.push(Broadcast.Util.makeTabPanel({key: 0}));
                $.each(createDate, function (index, obj) {
                    htmlArr.push(Broadcast.Util.makeTabPanel(obj))
                });

                $("input[name=clientSetting]").removeAttr("checked");
                $("input[name=clientSetting]" + "[value=0]").prop("checked", true);
                $("<div id='tabsDiv'></div>").html(htmlArr.join("")).appendTo($("#navDiv"));
                $("#navDiv").tabs({active: 0});
                $("#buttonDiv").show();
            },

//==================initTypeChannel end=============//
            episodeRun: function () {
                $("#buttonDiv").hide();
                $("#hintPart").hide();
                var channelId = Com.url.getParameter("id");
                if (channelId == null || isNaN(channelId)) {
                    EpgWeb.Plugin.showTips({content: "need channelId", type: "error"})
                    return;
                }
                var programId = Com.url.getParameter("programId");
                if (programId == null || isNaN(programId)) {
                    EpgWeb.Plugin.showTips({content: "need programId", type: "error"})
                    return;
                }
                var self = this;
                self.initDialog();
                self.dao.channelId = parseInt(channelId);
                self.dao.programId = parseInt(programId);
                Broadcast.Config.Mode = self.options.model;
                var taskArr = [];
                taskArr.push(self.task.getPlayPlatform(self.dao.cfgName.PlayPlatform, function (data) {
                    self.fillNavBar(data);
                }));
                taskArr.push(self.task.getChannel(self.dao.cfgName.getChannel, self.dao.channelId));
                taskArr.push(self.task.getBroadcastTask(self.dao.cfgName.broadcastControl, self.dao.channelId));
                taskArr.push(self.task.getProgramBroadcastTask(self.dao.cfgName.programbroadcastControl, self.dao.programId));
                $.each(taskArr, function (index, element) {
                    EpgWeb.ajaxQueue.push(element.regName, element.options);
                })

                EpgWeb.ajaxQueue.afterLoadComplete(function () {
                    self.initTypeEpisode();
                });
                EpgWeb.ajaxQueue.startLoad();
            },
            initTypeEpisode: function () {
                console.log("init end");
                var self = this;
                self.initPanelContainer();
                self.bindClickHandler();
                self.fillInitTabPanelDefault();
                self.fillInitTabPanel();
                self.initSuggestChannel();
                var channelEntity = self.dao.getChannel();
                if (channelEntity.liveType == 3) {
                    $("input[name=rejectSearch]").attr("disabled","disabled");
                    $("input[name=rejectSearch]").attr("checked",true);
                }
                //self.initLocationAreaMask();
            }
        })
    }
);